package com.zjf.fupload.popup.actions;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.MenuListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

/**
 * ftp资源右键菜单-基于表格的
 * @author zjf
 */
class RightMenuListener extends MouseAdapter {
	
	private ChoosePathDialog dialog;
	
	RightMenuListener(ChoosePathDialog dialog) {
		this.dialog = dialog;
	}
	
	 public void mouseDown(MouseEvent e) {  
		 
		 final Table table = dialog.getTable();
		 
         if (e.button == 3) {//鼠标右键
         	//获取选中的行
         	TableItem seletedItem = table.getItem(new Point(e.x, e.y));
         	
         	//在标题上时，返回为Null
         	//在空行上时，返回行所有的列里面的值都为空
         	if(seletedItem == null || seletedItem.getText(0).equals("")) {
         		return;
         	}
         	
         	//当在行进行点击鼠标右键时，该行就为选中状态
         	int selectedIdx = 0;
         	for(int i = 0; i < table.getItemCount(); i++) {
         		if(table.getItem(i) == seletedItem) {
         			selectedIdx = i;
         			break;
         		}
         	}
         	
         	table.select(selectedIdx);
         	
         	//第一行为"上级目录"，不出现菜单
         	if(selectedIdx == 0) {
         		return;
         	}
         	
			 Menu menu = new Menu(table);
			 
			 //菜单隐藏后，就取消表格的菜单，以便在其他非正常行上点击右键，不会出现菜单
			 menu.addMenuListener(new MenuListener() {
					@Override
					public void menuShown(MenuEvent event) {
						
					}
					
					@Override
					public void menuHidden(MenuEvent event) {
						table.setMenu(null);
					}
				});
			 
			 
             table.setMenu(menu);  
             MenuItem item = new MenuItem(menu, SWT.PUSH);  
             item.setText("删除");  
             
             item.addListener(SWT.Selection, new Listener() {  
                 public void handleEvent(Event event) {
                     TableItem item1 = (TableItem) table.getSelection()[0];  
                     Table parent = item1.getParent();  
                     if (parent != null) {  
                         table.remove(table.getSelectionIndices());  
                     }  
                     table.setMenu(null);
                 }  
             });  
         }  
	 }

}